package com.rd.student.jiaji.class1.jinhongyu._0724;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class Test04 {

    private static Semaphore semaphore = new Semaphore(20);

    public static void main(String[] args) {
        // 模拟50辆车 车进车出的场景
        for (int i = 0; i < 50; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()
                            + " 来到停车场");
                    // 返回可用的令牌数量
                    // 返回可用的车位数
                    if (semaphore.availablePermits() == 0) {
                        System.out.println("车位不足，请等待");
                    }
                    try {
                        // 获取车位
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()
                                + " 进入停车场");
                        Thread.sleep(new Random().nextInt(8888));
                        System.out.println(Thread.currentThread().getName()
                                + " 开出停车场");
                        // 释放车位
                        semaphore.release();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            thread.start();
        }
    }
}
